<template>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" center :width="dialogWidth" @close="handleDialogCancel()"
        destroy-on-close>
        <el-form :model="state.form" label-width="120px" :rules="rules" ref="ruleFormRef" status-icon>
            <el-form-item label="名称" prop="roleName">
                <el-input v-model="state.form.roleName" />
            </el-form-item>
            <el-form-item label="编码" prop="roleCode">
                <el-input v-model="state.form.roleCode" />
            </el-form-item>
            <el-form-item label="菜单" prop="menuIds">
                <el-tree-select v-model="state.form.menuIds" :data="treeData" multiple :render-after-expand="false"
                    show-checkbox check-strictly check-on-click-node style="width: 100%;" />
            </el-form-item>
            <el-form-item label="描述" prop="roleDesc">
                <el-input v-model="state.form.roleDesc" autosize type="textarea" />
            </el-form-item>
            <el-form-item label="状态" prop="active">
                <el-switch v-model="state.form.active" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleDialogCancel()">关闭</el-button>
                <el-button type="primary" @click="handleDialogConfirm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { list, remove, add, edit, getById } from '@/api/role'
import { menuAll } from '@/api/menu'
import { ElMessage, ElTable } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { dialogAutoWidth } from '@/utils/dialog'

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    roleName: [{ required: true, message: "角色名不能为空", trigger: 'blur' }],
    roleCode: [{ required: true, message: "编码不能为空", trigger: 'blur' }],
    active: [{ required: true, message: "状态不能为空", trigger: 'blur' }],
    menuIds: [{ required: true, message: "菜单不能为空", trigger: 'blur' }],
})

let dialogWidth = ref("30%")
// 生命周期
onMounted(() => {
    getWindowResize()
    get(state.form.id);
    getMenuAll(null);
})
// 获取屏幕尺寸
const getWindowResize = function () {
    dialogWidth.value = dialogAutoWidth;
}


let state = reactive<any>({
    form: {
        id: null,
        roleName: "",
        roleDesc: "",
        roleCode: "",
        active: true,
        menuIds: null,
    },
})

// 传值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        required: true,
        default: false,
    },
    dialogTitle: {
        type: String,
        required: true,
        default: '',
    },
    dialogData: {
        type: Object,
        default: () => { },
    }
})
// 监听
watch(() => props.dialogData, () => {
    state.form = props.dialogData;
}, { deep: true, immediate: true })

// 树形菜单数据
let treeData = ref()
// 获取菜单列表
let menus = ref<any[]>([])
const getMenuAll = async (params: any) => {
    let res: any = await menuAll(params);
    if (res.code == '200') {
        menus.value = res.data;
        // 递归树形结构数据
        treeData.value = transListToTreeData(menus.value, 0)
    }
}
// 根据ID查询
const get = async (id: number) => {
        if (state.form.id != null) {
            let res: any = await getById({ id: id });
            if (res.code == '200') {
                state.form = res.data;
            }
        }
}

// 事件派发
const emits = defineEmits(["dialogClose", "getListData"])

// 弹框中的取消按钮事件
const handleDialogCancel = () => {
    emits("dialogClose", false)
};

// 弹出框确定按钮事件
const handleDialogConfirm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
        if (valid) {
            let res: any = {};
            if (state.form.id == null) {
                res = await add(state.form);
            } else {
                res = await edit(state.form);
            }
            if (res.code == "200") {
                ElMessage.success(res.message)
                emits('getListData')
                handleDialogCancel();
            }
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 递归数组为树形
const transListToTreeData = (list: any, rootValue: any) => {
    let arr: any[] = []
    list.forEach((item: any) => {
        if (item.parentId === rootValue) {
            const children = transListToTreeData(list, item.id)
            if (children.length) {
                item.children = children
            }
            let data = {
                label: item.title,
                value: item.id,
                disabled: !item.active,
                children: item.children,
            }
            arr.push(data)
        }
    })
    return arr
}
</script>
<style lang="less" scoped>
</style>